package com.jackstraw.jack_base.datasource.jpa.base.dao.database.factory;

import com.jackstraw.jack_base.datasource.jpa.base.dao.database.JpaDao;
import com.jackstraw.jack_base.datasource.jpa.base.dao.database.SimpleJpaDao;
import com.jackstraw.jack_base.datasource.jpa.base.entity.po.JpaPo;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;

public class BaseRepositoryFactoryBean<DAO extends JpaDao<PO, ID>, PO extends ID, ID extends JpaPo<PO, ID>> extends JpaRepositoryFactoryBean<DAO, PO, ID> {
    /**
     * Creates a new {@link JpaRepositoryFactoryBean} for the given repository interface.
     *
     * @param repositoryInterface must not be {@literal null}.
     */
    public BaseRepositoryFactoryBean(Class<? extends DAO> repositoryInterface) {
        super(repositoryInterface);
    }


    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        return new BaseRepositoryFactory<PO, ID>(entityManager);
    }


    //创建一个内部类，该类不用在外部访问
    private static class BaseRepositoryFactory<PO extends ID, ID extends JpaPo<PO, ID>>
            extends JpaRepositoryFactory {

        private final EntityManager entityManager;

        public BaseRepositoryFactory(EntityManager entityManager) {
            super(entityManager);
            this.entityManager = entityManager;
        }

        @Override
        protected JpaRepositoryImplementation<?, ?> getTargetRepository(RepositoryInformation information, EntityManager entityManager) {
            return new SimpleJpaDao<PO, ID>((Class<PO>) information.getDomainType(), entityManager);
        }

        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return SimpleJpaDao.class;
        }
    }
}
